package com.gx.auth.service;

import com.gx.auth.dao.UserDAO;
import com.gx.auth.dao.UserRoleDAO;
import com.gx.auth.entity.User;
import com.gx.auth.entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;

/**
 * Created by Administrator on 2017/4/4.
 */
@Service
public class UserService {
    @Autowired
    private UserDAO userDAO;
    @Autowired
    private UserRoleDAO userRoleDAO;

    /**
     * 保存用户
     *
     * @param user
     * @return
     */
    public int addUser(User user) {
        return userDAO.insertUser(user);
    }

    /**
     * 更新用户信息0
     *
     * @param user
     * @return
     */
    public int updateUser(User user) {
        return userDAO.updataUserById(user);
    }

    /**
     * 根据id删除用户
     *
     * @param uid
     * @return
     */
    public int deleteUser(Long uid) {
        return userDAO.deleteUserById(uid);
    }

    /**
     * 登录认证
     *
     * @param name
     * @param pwd
     * @return
     */
    public User getUser(String name, String pwd) {
        return userDAO.findUserByinfo(name, pwd);
    }

    /**
     * 用户信息集合
     *
     * @param page
     * @param size
     * @return
     */
    public List<User> getUsers(int page, int size) {
        return userDAO.findPage(page, size);
    }

    /**
     * 用户ID集合查询对应用户信息
     *
     * @param ids
     * @return
     */
    public List<User> getUsers(Collection<Long> ids) {
        return (ArrayList) userDAO.findUserByids(ids);
    }

    /**
     * 分页查询用户角色对应关系
     *
     * @param page
     * @param size
     * @return
     */
    public List<UserRole> getUserRoles(int page, int size) {
        return userRoleDAO.selectUserRols(page, size);
    }

    /**
     * 根据用户id 号查询用户角色对应关系
     *
     * @param userId
     * @return
     */
    public List<UserRole> getUserRolesById(Long userId) {
        return userRoleDAO.selectUserRoleByUserId(userId);
    }


    /**
     * 保存用户角色对应关系
     *
     * @param userId
     * @param rolelds
     */
    public void addUserRoles(Long userId, Long[] rolelds) {
        List<UserRole> userRoles = new ArrayList<>();

        Arrays.asList(rolelds).forEach((roleid) -> {
            UserRole userRole = new UserRole();
            userRole.setRoleId(roleid);
            userRole.setUserId(userId);
            userRoles.add(userRole);

        });
        userRoleDAO.insertUserRoles(userRoles);
    }


}

